<template>
  <el-drawer v-model="drawer" :with-header="false" :size="drawerSize" @close="closeDrawer" :append-to-body="true" :modal="true" class="quotation-detail-drawer">
    <div class="project-detail">
      <div class="project-header">
        <div class="project-edit">
          <template v-if="editVisible">
            <el-button text type="primary" @click="submitOrder">提交</el-button>
            <el-button text type="primary" @click="editVisible = false">取消</el-button>
          </template>
          <el-button text type="primary" :icon="Edit" v-else @click="convertEdit"/>
        </div>
        <div class="project-title">
          <el-input v-if="editVisible" v-model="editForm.title" size="small" style="width: 300px" placeholder="请填写报价单主题" maxlength="64" clearable/>
          <template v-else>{{ quotationData.title }}</template>
        </div>
      </div>
      <div style="margin-left: 8%">
        <el-row style="line-height: 40px">
          <el-col :span="4">供应商：
            <template v-if="editVisible">
              <el-select v-model="editForm.supplierInfoId" size="small" style="width: 140px" @change="supplierChange" clearable filterable>
                <el-option v-for="item in supplierInfoList" :key="item.supplierInfoId" :value="item.supplierInfoId" :label="item.shortName"/>
              </el-select>
            </template>
            <template v-else>{{ quotationData.shortName }}</template>
          </el-col>
          <el-col :span="5">报价金额：
            <template v-if="editVisible">
              <el-input-number v-model="quotationData.amount" size="small" placeholder="请填写报价金额" :max="99999999" :min="0" :precision="2" :controls="false"/>
              <el-checkbox style="margin-left: 10px" v-model="quotationData.amountTax" label="是否含税" :true-label="1" :false-label="0" size="small"/>
            </template>
            <span v-else>{{ quotationData.amount.toFixed(2) }} （{{ quotationData.amountTax == 1 ? '含税' : '不含税' }}）</span>
          </el-col>
          <el-col :span="4">报价日期：
            <span v-if="editVisible">
              <el-date-picker v-model="editForm.quoteDate" style="width: 150px" type="date" placeholder="请选择报价日期" value-format="YYYY-MM-DD" size="small"/>
            </span>
            <span v-else>{{ quotationData.quoteDate }}</span>
          </el-col>
          <el-col :span="4" :offset="1">报价单归属人：{{ quotationData.userName }}</el-col>
          <el-col :span="2">来源：
            <span v-for="item in dictMap['orderSourceType']" :key="item.value" v-show="item.value == quotationData.source">{{ item.name }}</span>
          </el-col>
        </el-row>
      </div>

      <el-row>
        <el-col :span="8">
          <el-card :body-style="{ padding: `8px 10px` }" style="margin-right:10px;height: 100%" shadow="hover">
            <el-row align="middle" class="row-cell" style="justify-content: center;">
              <label class="label-tips" style="margin-right: 20px">订单辅助信息</label>
              <div class="button-item" @click="openMaterial('doc')">
                <el-icon color="var(--next-bg-menuBar-light-1)" size="16px">
                  <ele-Document/>
                </el-icon>
                <span class="tips">文档</span>
                <span>0</span>
              </div>
              <div class="button-item" style="margin-left: 25px" @click="openMaterial('file')">
                <el-icon color="var(--next-bg-menuBar-light-1)" size="16px">
                  <ele-Link/>
                </el-icon>
                <span class="tips">附件</span>
                <span>0</span>
              </div>
            </el-row>
            <el-row align="middle" class="row-cell">
              <label class="label-tips">报价单号</label>
              <div>{{ quotationData.quoteNo }}</div>
            </el-row>
            <el-row align="middle" class="row-cell">
              <label class="label-tips">经办人</label>
              <template v-if="editVisible">
                <el-select v-model="editForm.contactUserId" size="small" placeholder="请选择经办人" style="width: 160px" @change="contactChange" filterable clearable>
                  <el-option v-for="item in contactUsers" :key="item.id" :value="item.id" :label="item.name"/>
                </el-select>
              </template>
              <div v-else>
                <template v-for="item in contactUsers" :key="item.id">
                  <span v-if="item.id == quotationData.contactUserId">{{ item.name }}</span>
                </template>
              </div>
            </el-row>
            <el-row align="middle" class="row-cell">
              <label class="label-tips">联系电话</label>
              <el-input v-if="editVisible" v-model="editForm.contactPhone" style="width: 60%" size="small" placeholder="请填写联系人电话" maxlength="16" clearable/>
              <div v-else>{{ quotationData.contactPhone }}</div>
            </el-row>
            <el-row align="middle" class="row-cell">
              <label class="label-tips">交付说明</label>
              <el-input v-if="editVisible" type="textarea" style="width: 60%" size="small" v-model="editForm.submitExplain" :rows="2"/>
              <div v-else>{{ quotationData.submitExplain }}</div>
            </el-row>
            <el-row align="middle" class="row-cell">
              <label class="label-tips">运输说明</label>
              <el-input v-if="editVisible" type="textarea" style="width: 60%" size="small" v-model="editForm.transportExplain" :rows="2"/>
              <div v-else>{{ quotationData.transportExplain }}</div>
            </el-row>
            <el-row align="middle" class="row-cell">
              <label class="label-tips">包装说明</label>
              <el-input v-if="editVisible" type="textarea" style="width: 60%" size="small" v-model="editForm.packageExplain" :rows="2"/>
              <div v-else>{{ quotationData.packageExplain }}</div>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="16">
          <el-card style="flex:1;height: 100%" :body-style="{ padding: `12px 0` }">
            <el-row justify="space-between" align="middle" style="padding:0 10px">
              <h4>产品清单</h4>
              <el-row justify="end">
                <el-button size="small" type="warning" @click="printData" :disabled="editVisible">
                  <el-icon>
                    <ele-Printer/>
                  </el-icon>
                  打印
                </el-button>
                <el-button size="small" type="primary" @click="editProducts" :disabled="editVisible">
                  <el-icon>
                    <ele-EditPen/>
                  </el-icon>
                  编辑
                </el-button>
              </el-row>
            </el-row>
            <div class="page-content" id="pageContainer">
              <el-form ref="ruleRefForm" size="small" :model="quotationData" label-width="120px" label-position="right" style="border: 1px solid var(--el-border-color-light)">
                <el-table :data="quotationData.productItems" size="small" :header-cell-style="{textAlign: 'center'}" :cell-style="{textAlign: 'center'}">
                  <el-table-column label="产品编号" prop="id" width="160"/>
                  <el-table-column label="产品名称" prop="name" width="120"/>
                  <el-table-column label="数量" prop="num" width="90"/>
                  <el-table-column label="单价(元)" prop="price" width="90"/>
                  <el-table-column label="总价(元)" prop="total" width="90"/>
                  <el-table-column label="规格/详情" prop="specification"/>
                </el-table>
                <el-form-item label="合计" style="margin-bottom:0;border-bottom:1px solid var(--el-border-color-light);font-size:14px;color:var(--el-color-danger)">{{ quotationData.productAmountSum || '-' }}</el-form-item>
                <el-form-item label="大写" style="margin-bottom:0;border-bottom:1px solid var(--el-border-color-light);font-weight:bold;font-size:14px;">{{ numToChinese(quotationData.productAmountSum || 0) }}</el-form-item>
                <el-form-item label="备注" style="margin-bottom:0">{{ quotationData.remark || '-' }}</el-form-item>
              </el-form>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-dialog v-model="productVisible" :close-on-click-modal="false" destroy-on-close width="60%" @close="productVisible = false" title="产品清单">
      <el-table :data="productsForm.productItems" stripe :header-cell-style="{textAlign: 'center'}" :cell-style="{textAlign: 'center'}">
        <el-table-column label="序号" type="index" width="75"/>
        <el-table-column label="产品名称" width="150" prop="name">
          <template v-slot="{row}">
            <el-select v-model="row.name" allow-create size="small" filterable default-first-option clearable>
              <el-option v-for="item in productNames" :key="item.id" :value="item.name" :label="item.name"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="型号" width="150" prop="ver">
          <template v-slot="{row}">
            <el-input v-model="row.ver" maxlength="64" size="small" clearable/>
          </template>
        </el-table-column>
        <el-table-column label="详情/规格" width="150" prop="specification">
          <template v-slot="{row}">
            <el-input v-model="row.specification" maxlength="255" size="small" clearable/>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="100" prop="num">
          <template v-slot="{row}">
            <el-input-number v-model="row.num" :min="0" :max="999999" size="small" :controls="false" style="width: 90%" @change="calAmount(row)"/>
          </template>
        </el-table-column>
        <el-table-column label="价格" width="130" prop="price">
          <template v-slot="{row}">
            <el-input-number v-model="row.price" :min="0" :max="999999" size="small" :controls="false" style="width: 90%" :precision="2" @change="calAmount(row)"/>
          </template>
        </el-table-column>
        <el-table-column label="小计" width="140" prop="total"/>
        <el-table-column label="备注" prop="remark">
          <template v-slot="{row}">
            <el-input v-model="row.remark" type="textarea" size="small" :rows="2"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="90">
          <template v-slot="{$index, row}">
            <el-button type="danger" :icon="Delete" text @click="removeProduct($index, row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="margin-top: 5px;width: 100%">
        <el-col :span="3" :offset="1">
          <el-button type="primary" :icon="Plus" @click="addProduct" text>添加</el-button>
        </el-col>
        <el-col :span="4" style="line-height: 40px">合计：{{ productsForm.productAmountSum }} 元</el-col>
        <el-col :span="6" style="line-height: 40px">大写：{{ numToChinese(productsForm.productAmountSum) }}</el-col>
      </el-row>
      <template #footer>
        <el-button size="small" @click="productVisible = false">关 闭</el-button>
        <el-button size="small" type="primary" @click="productSubmit">保 存</el-button>
      </template>
    </el-dialog>

    <div class="tabs-list">
      <div class="close-btn" @click="drawer = false">
        <el-icon color="var(--next-color-white)" size="28px">
          <ele-CircleClose/>
        </el-icon>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import {computed, reactive, toRefs} from 'vue'
import {Edit, Plus, Delete} from '@element-plus/icons-vue'
import Cookies from 'js-cookie'
import {getDictByCodes} from '/@/api/sys/dict'
import {numToChinese} from '/@/utils/common'
import {getContactList} from '/@/api/supplier/supplierContact'
import {getSupplierSelector} from '/@/api/supplier'
import {editQuote} from '/@/api/supplier/quoteOrder'
import {ElMessage} from 'element-plus'
import purchaseApi from '/@/api/supplier/purchaseOrder'

export default {
  name: 'QuotationDetail',
  emits: ['callback', 'update:drawer'],
  props: {
    drawer: {
      type: Boolean,
      default: false
    },
    quotation: {
      type: Object,
      default: {
        id: null,
        title: null,
        orderNo: null,
        userName: null,
        contactName: null
      }
    }
  },
  setup(props, context) {
    const {quotation} = toRefs(props)
    const quotationData = computed({
      get: () => {
        let quotationOrderId = quotation.value.id
        if (quotationOrderId) {
          // 根据用户id获取用户在企业的名称
          quotation.value.userName = Cookies.get('userName')
          getSupplierSelector().then(res => state.supplierInfoList = res.data).catch(e => console.log(e))
          // 获取供应商联系人列表
          getContactList(quotation.value.supplierInfoId).then(res => state.contactUsers = res.data).catch(e => console.log(e))
          getDictByCodes(['orderSourceType']).then(res => state.dictMap = res.data).catch(e => console.log(e))
        }
        return quotation.value
      },
      set: val => context.emit('update:quotation', val)
    })
    const state = reactive({
      editVisible: false,
      editForm: {},
      dictMap: {
        orderSourceType: []
      },
      supplierInfoList: [],
      contactUsers: [],
      productsForm: {},
      tempId: 0,
      productVisible: false,
      productNames: [],
      drawerSize: document.body.clientWidth <= 1400 ? '1220px' : '85%'
    })

    // 打开文档doc/附件file对话框
    const openMaterial = (type) => {

    }
    // 打开编辑报价单的清单
    const editProducts = () => {
      // 获取产品清单名称
      purchaseApi.getHistoryProducts().then(res => state.productNames = res.data).catch(e => console.log(e))
      state.productsForm = {
        id: quotationData.value.id,
        productAmountSum: quotationData.value.productAmountSum,
        productItems: JSON.parse(JSON.stringify(quotationData.value.productItems))
      }
      state.tempId = 0
      state.productVisible = true
    }
    // 移除产品行
    const removeProduct = (index, product) => {
      state.productsForm.productItems.splice(index, 1)
      state.productsForm.productAmountSum -= product.total
    }
    // 打印数据
    const printData = () => {

    }
    // 转换页面编辑状态
    const convertEdit = () => {
      state.editForm = JSON.parse(JSON.stringify(quotationData.value))
      state.editForm.productItems = null
      state.editVisible = true
    }
    // 提交修改报价单
    const submitOrder = () => {
      editQuote(state.editForm).then(res => {
        if (res.data) {
          quotationData.value.title = state.editForm.title
          quotationData.value.supplierInfoId = state.editForm.supplierInfoId
          quotationData.value.shortName = state.editForm.shortName
          quotationData.value.amount = state.editForm.amount
          quotationData.value.quoteDate = state.editForm.quoteDate
          quotationData.value.supplierInfoId = state.editForm.supplierInfoId
          quotationData.value.contactUserId = state.editForm.contactUserId
          quotationData.value.contactPhone = state.editForm.contactPhone
          quotationData.value.contactName = state.editForm.contactName
          quotationData.value.submitExplain = state.editForm.submitExplain
          quotationData.value.transportExplain = state.editForm.transportExplain
          quotationData.value.packageExplain = state.editForm.packageExplain
          ElMessage.success('保存成功！')
          state.editVisible = false
        }
      }).catch(e => console.log(e))
    }
    // 供应商改变
    const supplierChange = (supplierInfoId) => {
      for (let i = 0; i < state.supplierInfoList.length; i++) {
        let item = state.supplierInfoList[i]
        if (item.supplierInfoId == supplierInfoId) {
          state.editForm.shortName = item.shortName
          break
        }
      }
      getContactList(supplierInfoId).then(res => {
        state.contactUsers = res.data
        // 默认选中第一个联系人
        if (state.contactUsers != null && state.contactUsers.length > 0) {
          let item = state.contactUsers[0]
          state.editForm.contactUserId = item.id
          state.editForm.contactPhone = item.phone
          state.editForm.contactName = item.name
        }
      }).catch(e => console.log(e))
    }
    // 联系人改变
    const contactChange = (contactId) => {
      for (let i = 0; i < state.contactUsers.length; i++) {
        let item = state.contactUsers[i]
        if (item.id == contactId) {
          state.editForm.contactPhone = item.phone
          state.editForm.contactName = item.name
          break
        }
      }
    }
    // 产品合计
    const calAmount = (product) => {
      let total = 0
      product.total = ((product.num || 0) * (product.price || 0)).toFixed(2)
      state.productsForm.productItems.forEach(item => total += (item.num || 0) * (item.price || 0))
      state.productsForm.productAmountSum = total.toFixed(2)
    }
    const addProduct = () => state.productsForm.productItems.push({
      id: null,
      tempId: state.tempId++,
      name: null,
      ver: null,
      specification: null,
      num: 0,
      price: 0.00,
      total: 0.00,
      remark: null
    })
    const productSubmit = () => {
      editQuote(state.productsForm).then(res => {
        if (res.data) {
          quotationData.value.productItems = res.data.productItems
          quotationData.value.productAmountSum = res.data.productAmountSum
          ElMessage.success('保存成功！')
          state.productVisible = false
        }
      }).catch(e => console.log(e))
    }
    // 关闭详情页
    const closeDrawer = () => {
      context.emit('callback')
      context.emit('update:drawer', false)
    }

    return {
      Edit,
      Plus,
      Delete,
      ...toRefs(state),
      closeDrawer,
      quotationData,
      openMaterial,
      numToChinese,
      editProducts,
      printData,
      convertEdit,
      submitOrder,
      supplierChange,
      contactChange,
      calAmount,
      addProduct,
      productSubmit,
      removeProduct
    }
  }
}
</script>

<style scoped lang="scss">
.project-detail {
  padding: 10px;
  background: var(--next-bg-main-color);
  min-height: 100%;

  .project-header {
    position: relative;
    display: flex;

    .project-title {
      width: 97%;
      text-align: center;
      font-size: 18px;
      font-weight: bold;
    }

    .project-edit {
      width: 3%;

      :deep(.el-icon) {
        font-size: 18px !important;
        margin-right: 0;
      }
    }
  }

  .button-item {
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 12px;
    padding: 4px 6px;
    border-radius: 4px;
    border: 1px solid var(--el-color-primary-light-8);

    span {
      line-height: 20px;
      display: inline-block;
      margin-left: 8px;
      color: var(--next-bg-menuBar-light-1);
    }

    .tips {
      font-weight: bold;
      color: var(--next-bg-menuBar-light-1);
      margin-left: 2px;
    }

    &:hover {
      background: var(--el-color-primary-light-8);
    }
  }

  .label-tips {
    font-size: 12px;
    width: 100px;
    margin-right: 10px;
    display: block;
    text-align: right;
  }

  .row-cell {
    margin-bottom: 18px;

    &:first-child {
      margin-top: 18px;
    }

    .label-data {
      font-size: 12px;
      margin-right: 5px;
    }
  }

  .page-content {
    padding: 10px;

    :deep(.el-form) {
      border: 1px solid var(--el-border-color-light);
      margin-top: 10px;

      .el-form-item__label {
        border-right: 1px solid var(--el-border-color-light);
        height: 34px !important;
        line-height: 34px;
      }

      .el-form-item__content {
        padding-left: 10px;
      }

      .el-table__cell {
        border-right: 1px solid var(--el-border-color-light);
        box-sizing: border-box;

        &:last-child {
          border-right: none;
        }
      }
    }
  }
}

.fixed-right {
  position: fixed;
  right: 40px;
  bottom: 30px;
  z-index: 999;

  .fixed-cell {
    background: var(--next-bg-topBar);
    border-radius: 50%;
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: var(--el-color-primary);
    font-size: 32px;
    box-shadow: rgba(0, 0, 0, 0.1) 0 1px 3px 0, rgba(0, 0, 0, 0.06) 0 1px 2px 0;
    margin-top: 10px;
  }
}

.tabs-list {
  position: absolute;
  top: 90px;
  left: -50px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  overflow: auto;
  max-height: 100%;

  .close-btn {
    width: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    background: var(--el-color-primary);
    padding: 5px 0;
    border-radius: 5px 0 0 5px;
  }
}
</style>
<style lang="scss">
.quotation-detail-drawer {
  position: fixed;
  overflow: unset;
  background: var(--next-bg-main-color);
}
</style>
